<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;

/**
 * Class LoginController
 * @package App\Http\Controllers\Admin
 */
class LoginController extends Controller
{
    use AuthenticatesUsers;
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 登录
     */
    public function login()
    {
        if(Session::get('admin.username') && Session::get('admin.id'))
        {
            return redirect(url('admin/index'));
        }
        return view('Admin.Login.login');
    }

    /**
     * @param Request $request
     * 登录验证
     */
    public function checkLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'captcha' => 'required|captcha',
            'username'=>'required|min:3',
            'password'=>'required|min:5',
        ],[
            'required'=>":attribute不能为空",
            'between'=>":attribute长度必须在 :min 和 :max 之间"
        ],[
            "captcha" => '验证码',
            'username' => '用户名',
            'password' => '用户密码',
        ]);
        if(!$validator->fails())
        {
            if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
                $user = AdminUser::where(['username'=>$request->username])->first();
                if($user->status == 1) {
                    Session::put('admin.username', 'admin');
                    Session::put('admin.id', $user->id);
                    Session::put('admin.role', $user->role);
                    Session::save();
                    return redirect(url('admin/index'));
                }else{
                    return back()->withInput()->withErrors(['该账户被禁用']);
                }
            }
            else{
                return back()->withInput()->withErrors(['密码错误']);
            }
        }else{
            $errors = $validator->errors();
           if($errors->has('captcha')) {
               return back()->withInput()->withErrors(['请输入正确的验证码']);
           }else {
               return back()->withInput()->withErrors(['请输入正确的账户信息']);
           }
        }
    }


    /**
     * @param Request $request
     * @return array
     * 点击更换图片
     */
    public function generateCaptcha(){
        return ['captcha'=>captcha_src()];
    }

    /**
     * 登出
     */
    public function logout()
    {
        Session::flush();
        return redirect(url('admin/login'));
    }

}
